package org.jeecg.modules.commu;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.boot.starter.rabbitmq.client.RabbitMqClient;
import org.jeecg.modules.device.Device;

@Slf4j
public class ClientConnection {

    NettyClientInitializer initlizer = new NettyClientInitializer();
    String ip;
    int port;
    boolean isConnected = false;

    ChannelFuture future = null;
    EventLoopGroup group = new NioEventLoopGroup();

    public ClientConnection(String ip, String port) {
        this.ip = ip;
        this.port = Integer.parseInt(port);
        this.isConnected = false;

    }

    public boolean isConnected(){
        return this.isConnected;
    }

    String connDeviceId = null;

    public void registerRabbitMq(RabbitMqClient client) {
        this.initlizer.getNettyClinetHandler().registerRabbitMq(client);
    }


    public void setDeviceId(String deviceId) {
        this.connDeviceId = deviceId;
        this.initlizer.getNettyClinetHandler().setDeviceId(deviceId);
    }

    public boolean start() {
        //EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap()
                .group(group)
                //该参数的作用就是禁止使用Nagle算法，使用于小数据即时传输
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
                .channel(NioSocketChannel.class)
                .handler(initlizer);

        try {
            future = bootstrap.connect(ip, port);
            future = future.sync();
            this.isConnected = true;
            log.info("客户端成功....");

            //发送消息
            //future.channel().writeAndFlush("hellow world");
            // 等待连接被关闭
            //future.channel().closeFuture().sync();
            return true;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            //group.shutdownGracefully();
        }
        this.isConnected = false;
        return false;
    }

    public synchronized void sendData(final String msg) {
//        if(future.channel() != null && future.channel().isActive())
//            future.channel().writeAndFlush(msg);

        //把ChannelFutureListener对象传递给EventLoopGroup线程，EventLoopGroup线程建立好连接以后调用operationComplete方法。
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                Channel channel = channelFuture.channel();
                //打印nioEventLoopGroup线程
                log.info("channel==========={}", channel);
                //向服务器发送数据
                channel.writeAndFlush(msg);
            }
        });
    }

    public void disconnect() {
        future.addListener(ChannelFutureListener.CLOSE);
        group.shutdownGracefully();
        this.isConnected = false;
    }

}
